﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.UI;
using JSC.Core;
using JSC.Portal.Entities;
using JSC.Portal.Entities.Interfaces;

namespace JSC.Portal.Web.Helper
{
    public class TreeViewRenderer<T> where T : IComposite<T>
    {
        private readonly Func<T, string> _locationRenderer;
        private readonly IEnumerable<T> _rootLocations;
        private HtmlTextWriter writer;

        public TreeViewRenderer(IEnumerable<T> rootLocations, Func<T, string> locationRenderer)
        {
            _rootLocations = rootLocations;
            _locationRenderer = locationRenderer;
        }
        public string Render()
        {
            writer = new HtmlTextWriter(new StringWriter());
            RenderLocations(_rootLocations);
            return writer.InnerWriter.ToString();
        }

        /// <summary>
        /// Recursively walks the location tree outputting it as hierarchical UL/LI elements
        /// </summary>
        /// <param name="locations"></param>
        private void RenderLocations(IEnumerable<T> locations)
        {
            if (locations == null) return;
            if (locations.Count() == 0) return;
            InUl(() => locations.ForEach(location => InLi(() =>
            {
                writer.Write(_locationRenderer(location));
                RenderLocations(location.Children);
            })));
        }

        private void InUl(Action action)
        {
            writer.WriteLine();
            writer.RenderBeginTag(HtmlTextWriterTag.Ul);
            action();
            writer.RenderEndTag();
            writer.WriteLine();
        }

        private void InLi(Action action)
        {
            writer.RenderBeginTag(HtmlTextWriterTag.Li);
            action();
            writer.RenderEndTag();
            writer.WriteLine();
        }
    }
}
